package game

import (
	"context"
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/manager"
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/protos"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	"github.com/topfreegames/pitaya/logger"
)

type GameHandler struct {
	component.Base
}

func NewGameHandler() *GameHandler {
	return &GameHandler{}
}

/**
初始化游戏
 */
func (p *GameHandler) InitGame(ctx context.Context,req *protos.CGInitGame) (*protos.GCInitGameRet,error) {
	s := pitaya.GetSessionFromCtx(ctx)
	playerId := *req.PlayerId
	logger.Log.Debugf("[GameHandler] InitGame PlayerId:%d is connecting",playerId)

	daemon := pitaya.ThreadPool.GetThread(constants.DaemonThread).(*manager.DaemonThread)
	if daemon != nil && daemon.IsAlive() {
		pUser := daemon.GetFromDisConnectPlayerList(s.UID())
		if pUser != nil && pUser.MGameState == model.PlayerLoginNormal {//等待玩家重新连接
			return &protos.GCInitGameRet{
				RetCode: &constants.InitGameWaitConnect,
			},nil
		}
	}

	serverId := pitaya.GetServerID()
	playerAuthRet := &protos.WGPlayerAuthRet{}
	err := pitaya.RPC(ctx, constants.GWPlayerAuthRoute,playerAuthRet,&protos.GWPlayerAuth{
		AccountId: req.AccountId,
		PlayerId:  req.PlayerId,
		Ticket:    req.Ticket,
		AppId:     req.AppId,
		ServerId:  &serverId,
	})

	if err != nil {
		logger.Log.Errorf("InitGame failed,error=%s",err.Error())
		return nil,err
	}

	retCode := playerAuthRet.RetCode
	if *retCode != constants.InitGameAutuSuccess {
		return &protos.GCInitGameRet{
			RetCode:       retCode,
		},nil
	}

	//处理认证成功逻辑



	return nil,nil
}